package com.optitronics.validators;

import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import com.optitronics.beans.Reseller;
import com.optitronics.ui.ResellerForm;

/**
 * Validates reseller form. 'taxNumber' and 'email' must be unique
 * 
 * @author Bojan Vukotic
 * 
 */
@Component
public class ResellerValidator {

	@Autowired
	private PasswordValidator passwordValidator;

	public void validateForm(ResellerForm formObject, Errors errors) {

		Reseller reseller = Reseller.findResellerByTaxNumber(formObject.getTaxNumber());
		if (reseller != null && reseller.getTaxNumber().equals(formObject.getTaxNumber())
				&& !reseller.getId().equals(formObject.getId())) {
			errors.rejectValue("taxNumber", "error.reseller.tax.number.exist");
		}

		if (!EmailValidator.getInstance().isValid(formObject.getEmail())) {
			errors.rejectValue("email", "field_invalid_email");
		} else {
			reseller = Reseller.findResellerByEmail(formObject.getEmail());
			if (reseller != null && reseller.getEmail().equals(formObject.getEmail())
					&& !reseller.getId().equals(formObject.getId())) {
				errors.rejectValue("email", "error.reseller.email.exist");
			}
		}

		if (formObject.getId() == null) {
			passwordValidator.validatePasswordsMatch(formObject, errors);
		}
	}

	public void validateResetPassowrd(ResellerForm formObject, Errors errors) {

		Reseller reseller = Reseller.findResellerByEmailAndTaxNumber(formObject.getEmail(), formObject.getTaxNumber());
		if (reseller == null) {
			errors.rejectValue("taxNumber", "error.reseller.email.tax.number.does.not.exist");
		}

	}
}
